package com.haidechizi.i18n.code.generator.common.message.translate.erai;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.haidechizi.i18n.code.generator.common.message.translate.mapping.LanguageMappingHolder;
import com.haidechizi.i18n.code.generator.common.message.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wangdejun
 */
@Slf4j
public class ErAiUtils {

    public static String translate(String data, String currentLanguage, String language, String appCode) {
        currentLanguage = LanguageMappingHolder.boundingMapping(currentLanguage);
        language = LanguageMappingHolder.boundingMapping(language);
        String host = "https://trans.xiaohuaerai.com";
        String path = "/trans";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appCode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<>();
        Map<String, String> bodys = new HashMap<>();
        bodys.put("d", language);
        bodys.put("q", data);
        bodys.put("s", currentLanguage);

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            String result = EntityUtils.toString(response.getEntity());
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSON.parseObject(result, JSONObject.class);
                if (200 == (int) jsonObject.get("status")) {
                    return String.valueOf(jsonObject.get("msg"));
                }
            }
        } catch (Exception e) {
            log.error("翻译失败", e);
        }
        return null;
    }
}
